<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="二线人员" prop="secondOperatorCode">
            <el-select v-model="formItem.secondOperatorCode" filterable clearable placeholder="请选择二线人员">
              <el-option v-for="(item) in users" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div style="float:right">
            <el-button size="mini" type="primary" @click="save()">提交</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

  </div>
</template>

<script>
import { secondLeaderCreate as create, secondLeaderDetail as detail } from '@neu/dcom-ui/api/alter'
import { list as userList } from '@neu/auth-ui/api/user'

const formItem = {
  // 工作流TaskId
  taskId: '',
  // 工单号
  workNum: '',
  // 操作人编码
  operatorCode: '',
  // 操作人姓名
  operatorName: '',
  // 二线操作人编码
  secondOperatorCode: '',
  // 二线操作人编码名称
  secondOperatorName: ''
}

const formRules = {
  secondOperatorCode: [{ required: true, message: '二线人员不能为空', trigger: 'blur' }]
}

export default {
  name: 'SecondLeaderForm',
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 二线工程师集合
      users: [],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: { ...formRules }
    }
  },
  created() {
    this.fetch()

    // 二线工程师
    userList({ 's_roleCode': 'expert' }).then(res => {
      this.users = res.data.map(e => { return { name: e.name, username: e.username } })
    })
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    save() {
      this.$refs.myform.validate((valid) => {
        if (valid) {
          // 二线工程师名称
          const one = this.users.find(e => e.username === this.formItem.secondOperatorCode)
          this.formItem.secondOperatorName = one ? one.name : ''

          // 设置工单号和任务
          this.formItem.taskId = this.taskId
          this.formItem.workNum = this.workOrderNum
          // 调用后台
          create(this.formItem).then(res => {
            if (res.status === 'success') {
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          })
        }
      })
    }
  }
}
</script>
